package com.smarttest.portal.service.timertask.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

/** 
 * 类说明 ：
 * @author hanjiancheng@chinawayltd.com: 
 * @version 创建时间：2010-5-19 下午02:39:49 
 *
 */

public class OutboxDaoDxt{
	
	private static final Logger log = LoggerFactory.getLogger(OutboxDaoDxt.class);
	
	private static final String API_URL = "http://smsservice.huoyunren.com/router/rest";
	private static final String APP_KEY = "112456";
	private static final String APP_SECRET = "684f8a";
	private static final String FORMAT = "json";
	
	private static final String SEND_METHOD = "huoyunren.sms.sender";

	
	public String insert(int userId, String mobileNo, String content, String source, String channel) {
		return insert(userId, mobileNo, content, source, channel, 0);
	}

	
	public String insert(int userId, String mobileNo, String content, String source, String channel, int type) {
		return insert(new OutboxItem(userId, mobileNo, content, source, channel, "7")); //默认encoding=‘7’
	}

	
	public String insert(OutboxItem item) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", item.getUserId());
		params.put("content", item.getContent());
		params.put("mobiles", item.getMobileNo());
		if (StringUtils.isNotBlank(item.getSource()))
			params.put("source", item.getSource());
		if (StringUtils.isNotBlank(item.getChannel())) {
			params.put("channel", item.getChannel());
		} else {
			params.put("channel", "smsDiexin");
		}
		try {
			ApiResult result = getResult(SEND_METHOD, params);
			if (result.getCode() != 0) {
				log.error("发送短信失败，返回信息：{}，短信内容：{}", result.getMessage(), item.getContent());
			}
			return result.getMessage();
		} catch (Exception e) {
			log.error("发送短信失败，返回信息：{}，短信内容：{}", e.getMessage(), item.getContent());
		}
		return "发送失败";
	}

	
	public int[] insert(List<OutboxItem> outboxList) {
		for (OutboxItem item : outboxList) {
			insert(item);
		}
		return new int[]{1};
	}

	
	private ApiResult getResult(String method, Map<String, Object> params) {
		params.put("app_key", APP_KEY);
		params.put("method", method);
		params.put("format", FORMAT);
		
		// 时间戳
		params.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        // 生成签名
        String sign = ApiUtil.sign(params, APP_SECRET);
        // 组装协议参数sign
        params.put("sign", sign);

        String result = ApiUtil.createRequestParam(params);
        
        result = ApiUtil.getResult(API_URL, result);
		return JSON.parseObject(result, ApiResult.class);
	}
	
	public static void main(String[] args) {
		OutboxDaoDxt daoDxt = new OutboxDaoDxt();
//		daoDxt.insert(userId, mobileNo, content, source, channel);
		daoDxt.insert(10, "13408517677", "测试监控", null, "dingtalk");

	}
}
